package com.zichong.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zichong.wiki.domain.Ebook;
import com.zichong.wiki.domain.EbookExample;
import com.zichong.wiki.mapper.EbookMapper;
import com.zichong.wiki.req.EbookQueryReq;
import com.zichong.wiki.req.EbookSaveReq;
import com.zichong.wiki.resp.EbookQueryResp;
import com.zichong.wiki.resp.PageResp;
import com.zichong.wiki.util.CopyUtil;
import com.zichong.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {

    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        // 创建一个 Criteria 相当于 Where 条件
        EbookExample.Criteria criteria = ebookExample.createCriteria();

        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }

        /**
         * 第一个参数pageNum是页码, 从 1 开始
         * 第二个参数pageSize是查询个数, 总页数 = total / pageSize, 假设是3, 那么总页数是 Math.ceil(总数/3)
         * 该分页插件只对第一次的 sql 语句生效, 中间如果穿插 sql 语句, 会失效
         * 因此分页写在最后查询的 sql 语句前面
         */
        PageHelper.startPage(req.getPage(),req.getSize());

        // 持久层返回 List<Ebook> 需要转成 List<EbookResp>, 再返回给 Controller
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数:{}", pageInfo.getTotal());
        LOG.info("总页数:{}", pageInfo.getPages());

        List<EbookQueryResp> respList = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);

        return pageResp;
    }

    /**
     * 保存
     */
    public void save(EbookSaveReq req) {
        // 将请求参数(req)变成实体(ebook)
        Ebook ebook = CopyUtil.copy(req, Ebook.class);

        if (ObjectUtils.isEmpty(req.getId())) {
            // 如果 id 是空的, 则新增
            // snowFlake 生成 id
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            // 如果 id 非空, 则更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
